package com.system.questionnairesurvey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.questionnairesurvey.common.util.constant.CommonConstants;
import com.system.questionnairesurvey.common.util.encryption.EncryptUtils;
import com.system.questionnairesurvey.common.util.response.R;
import com.system.questionnairesurvey.common.util.response.StringHelper;
import com.system.questionnairesurvey.common.util.validate.Regex;
import com.system.questionnairesurvey.entity.mybatis.UserEntity;
import com.system.questionnairesurvey.mapper.UserMapper;
import com.system.questionnairesurvey.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author wlh
 * @since 2022-04-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R login(String userCode, String password) {
        // 检验用户名和密码是否为空
        if (!userCode.isEmpty() && !password.isEmpty()) {
            R res = this.validateCodeAndPwd(userCode, password);
            UserEntity entity = (UserEntity) res.getData();
            // 登录认证
            if (entity != null) {
                String str = entity.getUserCode() + StringHelper.generateGUID() + System.currentTimeMillis();
                String accessToken = EncryptUtils.encodeBase64(str);
                redisTemplate.opsForValue().set(str, entity);
                redisTemplate.expire(str, 30, TimeUnit.MINUTES);
                entity.setToken(accessToken);
                return R.buildSuccess(entity);
            }
            return R.buildFail(res.getMsg());
        }
        return R.buildFail(CommonConstants.EMPTY_CODE_OR_PWD);
    }

    @Override
    public R saveUser(UserEntity user) {
        // 检验用户是否已经存在
        UserEntity existedUser = this.baseMapper.queryUserByUserCode(user.getUserCode(), null);
        if (Objects.nonNull(existedUser)) {
            return R.buildFail(CommonConstants.EXISTED_USER);
        }
        // 新增用户
        user.setPassword(EncryptUtils.MD5(CommonConstants.PWD, CommonConstants.SALT));//新增密码设置为初始化密码
        this.save(user);
        return R.buildSuccess(user);
    }

    @Override
    public R updateUser(UserEntity user) {
        UserEntity entity = this.baseMapper.queryUserByUserCode(user.getUserCode(), user.getId());
        // 检验是否已经存在此用户了
        if (Objects.nonNull(entity)) {
            return R.buildFail(CommonConstants.EXISTED_USER);
        }
        return this.updateById(user) ? R.buildSuccess(null) : R.buildFail(null);
    }

    @Override
    public R changPwd(Integer id, String oldPwd, String newPwd, String renewPwd) {
        UserEntity user = null;
        if (id != null) {
            user = this.getById(id);
        }
        if (user != null) {
            if (oldPwd == null || "".equals(oldPwd.trim())) {
                return R.buildFail("原密码不能为空");
            }
            if (newPwd == null || "".equals(newPwd.trim())) {
                return R.buildFail("新密码不能为空");
            }
            if (!newPwd.matches(Regex.CODE)) {
                return R.buildFail("新密码格式不正确");
            }
            if (renewPwd == null || "".equals(renewPwd.trim())) {
                return R.buildFail("确认密码不能为空");
            }
            if (!Objects.equals(EncryptUtils.MD5(oldPwd.trim(), CommonConstants.SALT), user.getPassword())) {
                return R.buildFail("输入原密码错误");
            }
            if (!newPwd.matches(Regex.CODE)) {
                return R.buildFail("新密码格式错误");
            }
            if (!newPwd.trim().equals(renewPwd.trim())) {
                return R.buildFail("两次输入的新密码不一致");
            }
            user.setPassword(EncryptUtils.MD5(newPwd, CommonConstants.SALT));

            return this.updateById(user) ? R.buildSuccess(null) : R.buildFail(null);
        }
        return R.buildFail(CommonConstants.NO_USER);
    }

    @Override
    public R listUsers(String key, Integer num, Integer size) {
        PageHelper.startPage(num, size);
        List<UserEntity> userEntities = listByCommon(key);
        return R.buildSuccess(new PageInfo<>(userEntities));
    }

    private List<UserEntity> listByCommon(String key) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.like(Objects.nonNull(key), "name", key);
        return list(wrapper);
    }

    private R validateCodeAndPwd(String userCode, String password) {
        UserEntity entity = this.baseMapper.queryUserByUserCode(userCode, null);
        // 检验用户是否存在
        if (entity == null) {
            return R.buildFail(CommonConstants.NO_USER);
        }
        // 检验用户状态
        if (entity.getStatus() != 0) {
            return R.buildFail(CommonConstants.NO_AUTH);
        }
        // 检验用户密码
        String queryPassword = entity.getPassword();
        if (!queryPassword.equals(EncryptUtils.MD5(password, CommonConstants.SALT))) {
            return R.buildFail(CommonConstants.FAIL_CODE_OR_PWD);
        }
        return R.buildSuccess(entity);
    }
}
